package com.skywolf.chem.usercenterapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.skywolf.chem.usercenterapi.service.WxService;
import com.skywolf.chem.utils.HttpUtils;
import com.skywolf.chem.utils.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by pei_pei on 2020/11/10.
 */
@Slf4j
@Service
public class WxServiceImpl implements WxService {

    @Override
    public String getAccessToken() {
        String appid = SysConfig._this.getProperty("wechatgz.appid");
        String appsecret = SysConfig._this.getProperty("wechatgz.appsecret");

        Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("appid",appid);
        paramsMap.put("secret",appsecret);
        paramsMap.put("grant_type","client_credential");
        String resp = HttpUtils.getMap("https://api.weixin.qq.com/cgi-bin/token", paramsMap);
        if(StringUtils.isBlank(resp)){
            log.info("WxServiceImpl.getAccessToken  request:{},resp:{}", JSON.toJSONString(paramsMap),resp);
            return " ";
        }
        JSONObject obj = JSONObject.parseObject(resp);
        String accessToken = obj.getString("access_token");
        return accessToken;
    }

    @Override
    public String getJsapiTicket(String token) {
        Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("access_token",token);
        paramsMap.put("type","jsapi");
        String resp = HttpUtils.getMap("https://api.weixin.qq.com/cgi-bin/ticket/getticket", paramsMap);
        if(StringUtils.isBlank(resp)){
            log.info("WxServiceImpl.getJsapiTicket  request:{},resp:{}", JSON.toJSONString(paramsMap),resp);
            return " ";
        }
        JSONObject obj = JSONObject.parseObject(resp);
        String ticket = obj.getString("ticket");
        return ticket;
    }
}
